package com.yc.jpyy.wxuser.controller;

import com.alibaba.fastjson.JSON;
import com.common.utils.manydatasource.HandlerDataSource;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.utils.Tools;
import com.yc.jpyy.wxuser.service.WxUserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信用户管理
 * by:何创强
 */
@Controller
@RequestMapping(value = "/wxuser")
@Scope("prototype")
public class WxUserController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(WxUserController.class);

    @Autowired
    private WxUserService wxUserService;

    /**
     *  根据姓名、身份证号 判断司机是否存在（是否是从业人员）
     *  name 姓名
     *  cardId 身份证
     * @param info
     * @return
     */
    @RequestMapping(value = "/isExistDriver",method = {RequestMethod.GET,
            RequestMethod.POST }, produces = "application/json; charset=utf-8")
    @ResponseBody
    public RestResponse isExistDriver(String info,HttpServletRequest request) {
        logger.info("根据姓名、身份证号 判断司机是否存在：",info);
        RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
        try{
            Map<String,Object> paramsMap = Tools.JsonToMap(info);
            HandlerDataSource.setDataSource(paramsMap.get("dbcode").toString());
            Object driver = this.wxUserService.getDriver(paramsMap);
            if(driver != null){
                response.setReturnMsg(1,"获取成功");
                response.setListData(driver);
            }else{
                response.setReturnMsg(0,"验证失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.info(e.getMessage());
            response.setReturnMsg(0,"判断失败");
            response.setReturnException(e.toString());
        }finally {
            HandlerDataSource.clear();
        }
        return response;
    }

    /**
     * 绑定微信帐号
     * @param info
     * @return
     */
    @RequestMapping(value = "/boundWx",method = {RequestMethod.GET,
            RequestMethod.POST }, produces = "application/json; charset=utf-8")
    @ResponseBody
    public RestResponse boundWx(String info,HttpServletRequest request) {
        logger.info("绑定微信:",info);
        RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
        try{
            Map<String,Object> paramsMap = Tools.JsonToMap(info);
            HandlerDataSource.setDataSource(paramsMap.get("dbcode").toString());
            this.wxUserService.add(paramsMap);
            response.setReturnMsg(1,"绑定成功");
        }catch(Exception e){
            e.printStackTrace();
            logger.info(e.getMessage());
            response.setReturnException(e.getMessage());
            response.setReturnMsg(0,"绑定失败");
        }finally {
            HandlerDataSource.clear();
        }
        return  response;
    }

    /**
     * 修改微信帐号内容
     * @param info
     * @return
     */
    @RequestMapping(value = "/update",method = {RequestMethod.GET,
            RequestMethod.POST }, produces = "application/json; charset=utf-8")
    @ResponseBody
    public RestResponse update(String info,HttpServletRequest request) {
        logger.info("修改微信内容:",info);
        RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
        try{
            Map<String,Object> paramsMap = Tools.JsonToMap(info);
            HandlerDataSource.setDataSource(paramsMap.get("dbcode").toString());
            this.wxUserService.update(paramsMap);
            response.setReturnMsg(1,"修改成功");
        }catch(Exception e){
            e.printStackTrace();
            logger.info(e.getMessage());
            response.setReturnException(e.getMessage());
            response.setReturnMsg(0,"修改失败");
        }finally {
            HandlerDataSource.clear();
        }
        return  response;
    }

    /**
     * 获取微信信息内容
     * @param info
     * @return
     */
    @RequestMapping(value = "/findById",method = {RequestMethod.GET,
            RequestMethod.POST }, produces = "application/json; charset=utf-8")
    @ResponseBody
    public RestResponse findById(String info,HttpServletRequest request) {
        logger.info("获取微信信息内容:",info);
        RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
        try{
            Map<String,Object> paramsMap = Tools.JsonToMap(info);
            HandlerDataSource.setDataSource(paramsMap.get("dbcode").toString());
            Map<String,Object> val = this.wxUserService.findById(paramsMap);
            if(val.size() == 0){
                response.setReturnMsg(0,"查无数据");
            }else{
                response.setListData(val);
                response.setReturnMsg(1,"查询单条数据成功");
            }

        }catch(Exception e){
            e.printStackTrace();
            logger.info(e.getMessage());
            response.setReturnException(e.getMessage());
            response.setReturnMsg(0,"查询失败");
        }finally {
            HandlerDataSource.clear();
        }
        return  response;
    }
    
    
    /**
     * 根据参数要求返回微信用户数据(记录条数)
     * @param info
     * @return
     * @throws UnsupportedEncodingException 
     */
    @SuppressWarnings("finally")
	@RequestMapping(value = "/getWxUserList",method = {RequestMethod.GET,
            RequestMethod.POST }, produces = "application/json; charset=utf-8")
    public @ResponseBody String getWxUserList(HttpServletRequest request) throws UnsupportedEncodingException {
    	request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = wxUserService.getWxUserList(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("addWeekCheck" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "获取失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
    }

	
	/**
	 * 根据openID查询是否绑定
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/checkIsBind", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String checkIsBind(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = wxUserService.checkIsBind(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("checkDriverIsBind" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	
	
	/**
	 * 绑定
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addBind", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String addBind(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = wxUserService.addBind(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("addBindForDriver" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "绑定失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	
	
	
	
	 //新增
		@SuppressWarnings("finally")
		@RequestMapping(value = "/updateGuanZhuWxuserQX", method = { RequestMethod.GET,
				RequestMethod.POST }, produces = "application/json; charset=utf-8")
		public @ResponseBody String updateGuanZhuWxuserQX(HttpServletRequest request) throws UnsupportedEncodingException {
			
			RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
			
			try{
				String info = request.getParameter("info");
				System.out.println("info"+info);
				//设置数据源
				Map<String,Object> paramsMap = Tools.JsonToMap(info);
				System.out.println("paramsMap"+paramsMap);
				String dbcode = paramsMap.get("dbcode").toString();
			    HandlerDataSource.setDataSource(dbcode);
			    int retValue =  wxUserService.updateGuanZhuWxuserQXService(paramsMap);
				logger.info("更新成功");
				System.out.println(retValue);
				response.setReturnMsg(1, "操作成功");
				return response.toJSON();
				
			} catch (Exception e) {
				logger.error("新增处理异常" + e.toString());
				// 异常信息
				response.setReturnCode(0);
				response.setReturnMsg("操作失败");
				response.setReturnException(e.toString());
				e.printStackTrace();
			}
			
			finally {
				HandlerDataSource.clear();
				return response.toJSON();
			}
			
		} //新增
		@SuppressWarnings("finally")
		@RequestMapping(value = "/addWxGongzhonghao", method = { RequestMethod.GET,
				RequestMethod.POST }, produces = "application/json; charset=utf-8")
		public @ResponseBody String addWxGongzhonghao(HttpServletRequest request) throws UnsupportedEncodingException {
			
			RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));	
			try{
				String info = request.getParameter("info");
				//设置数据源
				Map<String,Object> paramsMap = Tools.JsonToMap(info);
				String dbcode = paramsMap.get("dbcode").toString();
			    HandlerDataSource.setDataSource(dbcode);
			    response = wxUserService.addWxGongzhonghaoService(response,paramsMap);
			} catch (Exception e) {
				logger.error("新增处理异常" + e.toString());
				// 异常信息
				response.setReturnCode(0);
				response.setReturnMsg("操作失败");
				response.setReturnException(e.toString());
				e.printStackTrace();
			}
			finally {
				HandlerDataSource.clear();
				return response.toJSON();
			}
			
		}
		
		
	
	/**
	 * 更改
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateWxUserBlack", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateWxUserBlack(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = wxUserService.updateWxUserBlack(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("updateWxUserBlack" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "修改失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}

	/**
	 * 微信系统用户查询车辆信息
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getVehicleInfo", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getVehicleInfo(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			//String dbcode = paramsMap.get("dbcode").toString();
			//数据远设置成默认的总库查询试图，然后根据参数dbcode过滤符合条件的值
			HandlerDataSource.setDataSource("A1");
			String dbcode = Optional.ofNullable(paramsMap.get("dbcode")).orElse("").toString();
			paramsMap.put("dbcode",dbcode.equals("")?"":dbcode.split(","));
			resultMap = wxUserService.getVehicleInfo(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getVehicleInfo" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	
	
	/**
	 * 微信系统用户查询司机信息
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getDriverInfo", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getDriverInfo(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			//String dbcode = paramsMap.get("dbcode").toString();
			//数据远设置成默认的总库查询试图，然后根据参数dbcode过滤符合条件的值
			HandlerDataSource.setDataSource("A1");
			String dbcode = Optional.ofNullable(paramsMap.get("dbcode")).orElse("").toString();
			paramsMap.put("dbcode",dbcode.equals("")?"":dbcode.split(","));
			resultMap = wxUserService.getDriverInfo(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getDriverInfo" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	
	
	/**
	 * 微信系统用户查询车辆详情信息
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getVehicleInfoById", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getVehicleInfoById(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = wxUserService.getVehicleInfoById(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getVehicleInfoById" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	
	
	/**
	 * 微信系统用户查询司机详情信息
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getDriverInfoById", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getDriverInfoById(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String checkParameter= request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = wxUserService.getDriverInfoById(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getDriverInfoById" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	
	/**
	 * 检查用户是否关注公众号
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/checkOpenidIsExist", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String checkOpenidIsExist(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String,Object> resultMap = new HashMap<>();
		try {
			String info = request.getParameter("info");
			Map<String,Object> paramsMap = Tools.JsonToMap(info);
			HandlerDataSource.setDataSource("A1");
			resultMap = wxUserService.checkOpenidIsExist(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("checkOpenidIsExist" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "检查失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}
		
	}
	
	

}
